/*
 * DrawHalo.cpp
 *
 * An example of mouse event.
 * Mouse left button down to active drawing, mouse left button up to draw the circles.
 * With mouse move, a line will be drawn.
 *
 *  Created on: 2011-12-16
 *      Author: bala
 */
//#include "stdio.h"
#include "opencv/highgui.h"
#include "opencv/cv.h"

using namespace cv;

// Define mouse callback function
void mouse_callback( int event, int x, int y, int flags, void* param );

// Define draw circle function
void draw_halo( IplImage* img );

// Switch, when mouse left button down to set to true
bool drawing = false;

// Define the circle center point
CvPoint center;
// Define line start point
CvPoint pt1;
// Define circle radius
int radius = 5;

int main( int argc, char** argv ) {

	// Create an blank image
	IplImage* img = cvCreateImage( cvSize(640, 480), IPL_DEPTH_8U, 3 );
	// Set the data array to all 0, initial black image
	cvZero( img );
	// A temparary image will be used for drawing circles
	// Clone the image structure from img
	IplImage* temp = cvCloneImage( img );

	// Initial center point
	center = cvPoint( 0, 0 );
	pt1 = center;

	cvNamedWindow( "Draw Halo", CV_WINDOW_AUTOSIZE );

	// Set mouse callback function to the window defined above
	cvSetMouseCallback( "Draw Halo", mouse_callback, (void*) img );

	while( 1 ) {

		cvCopyImage( img, temp );

		if ( drawing ) {
			draw_halo( temp );
		}

		cvShowImage( "Draw Halo", temp );

		// fprintf(stderr, "%d", cvWaitKey(25));

		// Press ESC key to exit
		if ( cvWaitKey(1) == 1048603 ) break;
	}

	cvReleaseImage( &img );
	cvReleaseImage( &temp );
	cvDestroyWindow( "Draw Halo" );

	return 1;
}

void draw_halo( IplImage* img ) {
	int count = 5;
	int temp_radius = radius;

	while ( count-- ) {
		cvCircle( img, center, temp_radius, cvScalar( 0xff, 0x00, 0x00 ), 1 );
		cvWaitKey(1);
		temp_radius += 2;
	}
}

void mouse_callback( int event, int x, int y, int flags, void* param ) {

	IplImage* img = (IplImage*) param;

	switch (event) {
		case CV_EVENT_MOUSEMOVE: {
			if ( drawing ) {
				CvPoint pt2 = cvPoint(x, y);
				cvLine( img, pt1, pt2, cvScalar(0x00, 0xff, 0x00), 4);
				pt1 = pt2;
			}
		}
		break;

		case CV_EVENT_LBUTTONDOWN: {
			drawing = true;
			center = cvPoint( x, y );
			pt1 = center;
		}
		break;

		case CV_EVENT_LBUTTONUP: {
			if ( drawing ) {
				draw_halo( img );
			}
			drawing = false;
		}
		break;
	}
}

